import axios from 'axios'
import { message, Modal } from 'ant-design-vue'
import store from '@/store'
import { setToken, getToken, getRefreshToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || process.env.baseURL || '',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

function refreshToken() {
  const refreshToken = getRefreshToken()
  return service({
    url: '/oauth/refreshToken',
    method: 'post',
    data: { refreshToken }
  })
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.userToken) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['accessToken'] = getToken()
      // config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    if (response.config.responseType === 'blob') {
      return res
    }
    if (res.code !== 200) {
      if (res.code !== 401) {
        message.error(res.message || 'Error', 3)
        return Promise.reject(new Error(res.message || 'Error'))
      }

      const config = response.config
      if (isRefreshing) {
        // 正在刷新token，将返回一个未执行resolve的promise
        // 保存函数 等待执行
        // 吧请求都保存起来 等刷新完成后再一个一个调用
        return new Promise((resolve) => {
          // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
          requests.push((token) => {
            config.headers['accessToken'] = token
            resolve(service(config))
          })
        })
      }

      isRefreshing = true
      return refreshToken()
        .then((res2) => store.dispatch('user/refreshToken', res2.data))
        .catch(() => {
          // to re-login
          Modal.confirm({
            title: '您已注销，可以取消以保留在该页面上，或者再次登录',
            okText: '重新登录',
            cancelText: '取消',
            onOk() {
              return store.dispatch('user/resetToken').then(() => {
                location.reload()
              })
            },
            onCancel() {}
          })
          return Promise.reject(new Error(res.message || 'Error'))
        })
        .then(({ token }) => {
          requests.forEach((cb) => cb(token))
          return service(config)
        })
        .finally(() => {
          console.log('token refreshed')
          requests = []
          isRefreshing = false
        })
    }
    return res
  },
  (error) => {
    console.log('err' + error) // for debug
    message.error(error.message || 'Error', 3)
    return Promise.reject(error)
  }
)

export default service
